import React, {Component} from 'react';
import {
    View, Text, TextInput,
    StyleSheet,
    AsyncStorage
} from 'react-native';

import {
    Input, Card, Button
} from 'react-native-elements';
import Icon from 'react-native-vector-icons/Feather'
import {observable, computed, action, autorun, runInAction} from 'mobx';
import {observer} from 'mobx-react';
import {Toast} from 'teaset'; 

import requests from '../../utils/requests';
import validators from '../../utils/validators';
import {URLs} from '../../constants';
import UserStore from '../../stores/UserStore';


@observer
export default class AuthRegisterScreen extends Component {
    state = {
        validationCodeButtonEnabled: false,
    };

    @observable sendingFetchValidationCodeRequest = false;
    @observable sendingRegisterRequest = false;

    @observable phoneNumber = null;
    @observable invitationCode = null;
    @observable validationCode = null;
    @observable password = null;

    @computed get validationCodeButtonEnabled() {
        return validators.phoneNumber(this.phoneNumber) &&
                validators.invitationCode(this.invitationCode) &&
                !this.sendingFetchValidationCodeRequest;
    }
    @computed get registerButtonEnabled() {
        return !UserStore.loggedIn &&
                validators.phoneNumber(this.phoneNumber) && 
                validators.invitationCode(this.invitationCode) &&
                validators.validationCode(this.validationCode) &&
                validators.password(this.password)
    }

    @action.bound
    _onPhoneNumberChanged(phoneNumber) {
        this.phoneNumber = phoneNumber;
    };
    @action.bound
    _onInvitationCodeChanged(invitationCode) {
        this.invitationCode = invitationCode;
    }
    @action.bound
    _onValidationCodeChanged(validationCode) {
        this.validationCode = validationCode;
    }
    @action.bound
    _onPasswordChanged(password) {
        this.password = password;
    }

    @action.bound
    _fetchValidationCode = () => {
        const url = `${URLs.fetchRegisterValidationCode}?phone=${this.phoneNumber}&code_invite=${this.invitationCode}`
        let msg = null;
        this.sendingFetchValidationCodeRequest = true;
        requests.get(url).then(json => {
            console.log(`Fetching validation code returns ${json}`);
            if (json == null) {
                msg = '发送验证码失败，请稍后再试';
                Toast.sad(msg);
            }
            console.log('Fetching validation code returns:', json);
            else {
                switch (json.code) {
                    case 1:
                        msg = '验证码已发送至您的手机，请查收';
                        Toast.smile(msg);
                        break;
                    case 7:
                        msg = '该手机号已注册';
                        Toast.sad(msg);
                        break;
                    case 8:
                        msg = '验证码已发送，请等待手机接收';
                        Toast.sad(msg);
                        break;
                    case 9:
                        msg = '邀请码错误，请核对后重试';
                        Toast.sad(msg);
                        break;
                    default:
                        msg = '发送验证码失败，请稍后再试';
                        Toast.sad(msg);
                }
            }
            runInAction(() => {
                this.sendingFetchValidationCodeRequest = false;
            });
        })
    }
    @action.bound
    _fetchRegistration = async () => {
        if (UserStore.loggedIn) {
            msg = '您已登录';
            Toast.smile(msg);
            return;
        }
        this.sendingRegisterRequest = true;
        let data = {
            phone: this.phoneNumber,
            code_check: this.validationCode,
            code_invite: this.invitationCode,
            password: this.password,
        };
        if (UserStore.wechatLoginInfo.openid !== null) {
            data.wechat_openid = UserStore.wechatLoginInfo.openid;
            data.wechat_unoinid = UserStore.wechatLoginInfo.unionid;
            data.wechat_headimgurl = UserStore.wechatLoginInfo.headimgurl;
            data.wechat_nickname = UserStore.wechatLoginInfo.nickname;
        }
        const ret = await requests.post(URLs.register, data);
        if (ret == null) {
            msg = '注册失败，请稍后再试';
            Toast.sad(msg);
            runInAction(() => {
                this.sendingRegisterRequest = false;
            });
            return;
        }
        else {
            switch (ret.code) {
                case 1:
                    msg = '注册成功';
                    Toast.smile(msg);
                    break;
                case 5:
                    msg = '验证码错误';
                    Toast.sad(msg);
                    break;
                case 6:
                    msg = '参数错误，请核对后重试';
                    Toast.sad(msg);
                    break;
                case 9:
                    msg = '邀请码错误，请核对后重试';
                    Toast.sad(msg);
                    break;
                case 10:
                    msg = '邀请码已失效，请重新发送';
                    Toast.sad(msg);
                    break;
                default:
                    msg = '注册失败，请稍后再试';
                    Toast.sad(msg);
            }
        }
        runInAction(() => {
            this.sendingRegisterRequest = false;
        });

        if (ret != null && ret.code === 1) {
            runInAction(() => {
                try {
                    UserStore.login();
                }
                catch (e) {}
            });
            console.log('User registered.')
            this.props.navigation.navigate('tabRouter');
        }
    }

    render() {
        console.log('Auth register', this.props.navigation.parmas);
        return (
            <View style={styles.container}>
                <View style={styles.form}>
                    <TextInput
                        placeholder='请输入手机号'
                        autoCapitalize={'none'}
                        keyboardType={'numeric'}
                        onChangeText={this._onPhoneNumberChanged}
                    />
                    <TextInput
                        placeholder='请输入邀请码'
                        autoCapitalize={'none'}
                        keyboardType={'numeric'}
                        onChangeText={this._onInvitationCodeChanged}
                    />
                    <View style={{position: 'relative'}}>
                        <TextInput
                            placeholder='请输入验证码'
                            autoCapitalize={'none'}
                            keyboardType={'numeric'}
                            onChangeText={this._onValidationCodeChanged}
                        />
                        <Button
                            title='获取'
                            titleStyle={_styles.validationCodeButton.title}
                            buttonStyle={_styles.validationCodeButton.button}
                            containerStyle={_styles.validationCodeButton.container}
                            disabled={!this.validationCodeButtonEnabled}
                            onPress={this._fetchValidationCode}
                        />
                    </View>
                    
                    <TextInput
                        placeholder='请输入密码'
                        autoCapitalize={'none'}
                        secureTextEntry={true}
                        keyboardType={'numeric'}
                        onChangeText={this._onPasswordChanged}
                    />
                    <View style={styles.formButtonGroup}>
                        <Button
                            title='注册'
                            titleStyle={_styles.loginButton.title}
                            buttonStyle={_styles.loginButton.button}
                            containerStyle={_styles.loginButton.container}
                            disabled={!this.registerButtonEnabled}
                            onPress={this._fetchRegistration}
                        />
                    </View>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
    },
    form: {
        width: '80%',
        marginTop: '30%',
    },
});

const _styles = {
    loginButton: {
        container: {
            marginTop: 10,
        },
    },
    validationCodeButton: {
        title: {
            fontSize: 10,
        },
        button: {
        },
        container: {
            position: 'absolute',
            top: 5,
            right: 10,
            width: 40,
        }
    },
}